<template>
  <div>
    <Drawer
      ref="modal"
      :title="`${editType === 'create' ? $t('Attendance.AttendanceAdd') : $t('Attendance.AttendanceEdit')}`"
      width="70%"
      :value="show"
      :beforeClose="$_modal_decideIfClose"
    >
      <Form
        ref="form"
        :labelWidth="110"
        :model="formData"
        :rules="formRule"
      >
        <FormItem prop="areaName" :label="$t('Attendance.AttendanceNameE')">
          <Input v-model="formData.areaName" :placeholder="$t('Attendance.AttendanceNameIn')" style="width: 210px" />
        </FormItem>
        <FormItem prop="officeTime" :label="$t('Attendance.AttendanceGoTime')">
          <TimePicker v-model="formData.officeTime"  format="HH:mm" :placeholder="$t('Attendance.AttendanceTime')"></TimePicker>
        </FormItem>
        <FormItem prop="closingTime" :label="$t('Attendance.AttendanceOutTime')">
          <TimePicker v-model="formData.closingTime"  format="HH:mm" :placeholder="$t('Attendance.AttendanceTime')"></TimePicker>
        </FormItem>
         <FormItem prop="selectTime" :label="$t('Attendance.AttendanceData')" :required='true'>
          <RadioGroup v-model="formData.selectTime" @on-change='selectTimeC'>
            <Radio label="0" >
                <span>{{$t('Attendance.AttendanceCyclic')}}</span>
            </Radio>
            <Radio label="1" >
                <span>{{$t('Attendance.AttendanceCustom')}}</span>
            </Radio>
          </RadioGroup>
        </FormItem>

        <FormItem v-if="selectWeek" prop="workday" label="">
          <CheckboxGroup v-model="formData.workday">
            <Checkbox label="1">
                <span>{{$t('Attendance.AttendanceMonday')}}</span>
            </Checkbox>
            <Checkbox label="2">
                <span>{{$t('Attendance.AttendanceTuesday')}}</span>
            </Checkbox>
            <Checkbox label="3">
                <span>{{$t('Attendance.AttendanceWednesday')}}</span>
            </Checkbox>
            <Checkbox label="4">
                <span>{{$t('Attendance.AttendanceThursday')}}</span>
            </Checkbox>
            <Checkbox label="5">
                <span>{{$t('Attendance.AttendanceFriday')}}</span>
            </Checkbox>
            <Checkbox label="6">
                <span>{{$t('Attendance.AttendanceSaturday')}}</span>
            </Checkbox>
            <Checkbox label="7">
                <span>{{$t('Attendance.AttendanceSUN')}}</span>
            </Checkbox>
          </CheckboxGroup>
        </FormItem>

        <FormItem v-if="!selectWeek" prop="customDay" label="">
          <DatePicker format="yyyy-MM-dd" v-model="formData.customDay" :value="formData.customDay" type="date" multiple :placeholder="$t('Attendance.AttendanceTimeS')" style="width: 300px"></DatePicker>
        </FormItem>
        <FormItem :label="$t('AccessIndex.AccessJobdeNum')">
          <div class="item" style="float:left;margin-right:40px">
            <Cascader :data="recordTypes" v-model="recordType"
              @on-change="handleChange1" :clearable="false"
              change-on-select>
            </Cascader>
          </div>
        </FormItem>
        <FormItem class="personList" prop="mids" :label="$t('Attendance.AttendanceSelNum')">
          <div class="action">
            <div class="itemTitle">
              <Checkbox class="checkBox"
                :value="allCheck"
                @on-change="handleSlectAll"
              >{{ $t("areaIndex.areaSearchAll") }}</Checkbox>
              <div class="num">
                <span>{{departName}}{{ $t("newDevices.total") }}{{ personList.length }}{{ $t("BodyTemperatureIndex.BodyTemAnimalMan") }}</span>&nbsp&nbsp&nbsp&nbsp
                <span>{{ $t("devicesIndex.devSelected") }}{{ checkDNum }}</span>
              </div>
            </div>
            <div class="itemTitle ml">
              <div class="num">
                <!-- <span>{{departName}}{{ $t("newDevices.total") }}{{ personList.length }}{{ $t("BodyTemperatureIndex.BodyTemAnimalMan") }}</span>&nbsp&nbsp&nbsp&nbsp -->
                <span>{{ $t("areaIndex.areaSearchSelected") }}{{ formData.mids.length }}</span>
              </div>
            </div>
            
          </div>
          <div class="list" ref="personList">
            <div class="person-list"  >
              <RecycleScroller
                class="scroller person-item"
                :items="personList"
                :item-size="32"
                key-field="mid"
                v-slot="{ item }"
                :prerender="10"
                v-show="personList.length>0"
              >
                <div class="user">
                  <Checkbox
                    :value="item.checked"
                    @on-change="itemChange(item,item.checked)"
                  />
                  <Icon class="item-icon" type="md-contact" size="24" />
                  <div class="item-title">{{ item.username }}</div>
                  
                </div>
              </RecycleScroller>
              <div class="pl" v-show="personList&&personList.length<=0">{{this.$t('areaIndex.areaSearchNoData')}}</div>
            </div>
            <div class="person-list ml">
              <RecycleScroller
                class="scroller person-item"
                :items="formData.mids"
                :item-size="32"
                key-field="mid"
                v-slot="{ item }"
                v-show="formData.mids.length>0"
                :prerender="10"
              >
                <div class="user">
                  <Icon class="item-icon" type="md-contact" size="24" />
                  <div class="item-title">{{ item.username }}</div>
                  <!-- <template v-slot="{ index }">
                    <Icon class="close-icon" @click="delPerson(item,index)" type="md-close-circle" size="22" />
                  </template> -->
                  <Icon class="close-icon" @click="delPerson(item)" type="md-close-circle" size="22" />
                </div>
              </RecycleScroller>
              <div class="pl" v-show="formData.mids&&formData.mids.length<=0">{{this.$t('areaIndex.areaSearchNoData')}}</div>
            </div>
          </div>
          
        </FormItem>
        <FormItem class="glo-btn-group">
          <Button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
          >{{ $t("devicesCreate.devCreateSubmit") }}</Button>
          <Button
            @click="$_modal_close"
          >{{ $t("devicesCreate.devCreateCancel") }}</Button>
        </FormItem>
      </Form>
    </Drawer>
  </div>
</template>

<script>
import _ from 'lodash'
import {
  mapState,
} from 'vuex'
import {
  format
} from '@/utils/auth.js'
import modalMixin from '@/utils/mixins/modalMixin.js'
import {
  create,
  update,
  detail,
} from '@/api/Attendance.js'

import {
  selectAllPerson
} from '@/api/person.js'

import Vue from 'vue'
import { RecycleScroller } from 'vue-virtual-scroller'

Vue.component('RecycleScroller', RecycleScroller)
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";
const DEFAULT_FORM = {
  areaName: '',
  officeTime: '09:00',
  closingTime: '18:00',
  selectTime: '0',
  workday: ['1', '2', '3', '4', '5'],
  customDay: [],
  mids: [
    // { mid: 1, username: '陈一' },
    // { mid: 2, username: '陈二' },
    // { mid: 3, username: '陈三' },
  ],
}

export default {
  mixins: [
    modalMixin,
  ],
  components: {
    
  },

  props: {
    editType: {
      type: String,
      default: 'create',
    },
    editItem: Object,
  },
  data () {
    return {
      selectWeek: true,
      formData: _.cloneDeep(DEFAULT_FORM),
      formRule: {
        areaName: { required: true, message: this.$t('Attendance.AttendanceNameIn') },
        officeTime: { required: true, message: this.$t('Attendance.AttendanceGoTimeS') },
        closingTime: { required: true, message: this.$t('Attendance.AttendanceOutTimeS') },
        // mids: { required: true, message: this.$t('Attendance.AttendanceRelation') },
        // mids: { required: true, validator: (rule, value, callback) => {
          
        //   if (!reg.test(this.formData.contact)) {
        //     return callback(new Error(this.$t('Attendance.AttendanceRelation')))
        //   } else {
        //     return callback()
        //   }
          
        // }, trigger: 'blur' }, 
      },
      recordTypes: [],
      recordType: [],
      personList:[],
      depId:'',
      departName:'',
    }
  },
  computed: {
    ...mapState([
      'departId',
    ]),
    allCheck() {
      if(!this.personList||this.personList.length<=0){
        return false
      }else{
        // every 当数组中每一项都返回 true，整体才返回 true；有一项返回 false，整体就返回 false
        return this.personList.every(item => {
          return item.checked
        })
      } 
    },
    checkDNum() {
      if(!this.personList){
        return 0
      }else{
        // every 当数组中每一项都返回 true，整体才返回 true；有一项返回 false，整体就返回 false
        let num=0
        this.personList.map(item => {
          if(item.checked){
            num++
          }
        })
        return num
      } 
    }
  },

  mounted () {
    this.show = true
    this.getDataList()
    if (this.editType === 'update') {
      console.log(this.editItem.id)
      this.getDetail(this.editItem.id)
    }
  },

  methods: {
    selectTimeC (val) {
      console.log(val)
      // console.log(this.formData.customDay)
      if (val == '1') {
        this.selectWeek = false
        this.formRule.customDay = { required: true, message: this.$t('Attendance.AttendanceTimeS') }
        console.log(this.formRule)

        // {
        //   areaName: { required: true, message: this.$t('areaIndex.areaAddNameSure') },
        //   officeTime: { required: true, message: '选择上班时间'},
        //   closingTime: { required: true, message: '选择下班时间' },
        //   mids: { required: true, message: '选择考勤相关人员' },
        //   customDay: ,
        // }
      } else {
        this.selectWeek = true
        delete this.formRule.customDay
        console.log(this.formRule)
      }
    },
    async handleSubmit () {
      const ifVlid = await this.$refs.form.validate()
      if (ifVlid && this.editType === 'create') {
        this.handleCreate()
      }
      if (ifVlid && this.editType === 'update') {
        this.handleCreate()
      }
    },

    async getDetail (areaId) {
      console.log(areaId)
      var parma = {id: areaId}
      const { success, data } = await detail(parma)
      if (success) {
        const netForm = data.data
        const formData = {}
        // const keys = Object.keys(DEFAULT_FORM)
        // keys.forEach(key => {
        //   formData[key] = _.isUndefined(netForm[key])
        //     ? DEFAULT_FORM[key]
        //     : netForm[key]
        // })
        // formData.id = netForm.id


//  areaName: '',
//   officeTime: '',
//   closingTime: '',
//   selectTime: '0',
//   workday: ['周一', '周二', '周三', '周四', '周五'],
//   customDay: [],
        if (netForm.checkType == 0) {
          formData.workday = netForm.checkDate.split(',')
          formData.customDay = []
          this.selectWeek = true
        } else {
          formData.customDay = netForm.checkDate.split(',')
          formData.workday = ['1', '2', '3', '4', '5']
          this.selectWeek = false

        }

        formData.mids = netForm.personLableDto
        formData.areaName = netForm.name
        formData.officeTime = netForm.startTime
        formData.closingTime = netForm.endTime
        formData.selectTime = netForm.checkType
        this.formData = _.cloneDeep(formData)
      }
    },
    async handleCreate () {
      var aTime
      var aMids = []
      if (this.selectWeek) {
        aTime = this.formData.workday
      } else {
        // aTime = this.formData.customDay
        if (!this.formData.customDay[0]) {
          this.formData.customDay = []
        }
        if (this.formData.customDay.length != 0) {
          var arr = []
          this.formData.customDay.forEach((item, index) => {
            arr.push(format(item,'yyyy-MM-dd'))
          })
          aTime = arr
        } else {
          aTime = []
        }
      }
      if (aTime.length == 0) {
        this.$Message.error(this.$t('Attendance.AttendanceTimeS'))
        return
      }

      // if (this.formData.mids.length > 0) {
      //   this.formData.mids.forEach( (item,index) => {
      //     let New = {
      //       username: item.username,
      //       mid: item.mid,
      //     }
      //     aMids.push(New)
      //   })
      // }
      // this.personList.forEach(v=>{
      //   if(v.checked){
      //     let da={
      //       username:v.username,mid:v.mid
      //     }
      //     aMids.push(da)
      //   } 
      // })
      aMids=this.formData.mids
      if(aMids&&aMids.length<=0){
        this.$Message.error(this.$t("Attendance.AttendanceRelation"))
        return
      }
      // if(this.formData.mids.length>0){
      //   aMids=aMids.concat()
      // }
      var timeS = `2018-01-02 ${this.formData.officeTime}`
      var timeE = `2018-01-02 ${this.formData.closingTime}`
      var date = new Date(timeS);
		  var date1 = new Date(timeE);
      if (date.getTime() >= date1.getTime()) {
			this.$Message.error({
          content: this.$t("Attendance.AttendanceSTimes"),
          duration: 5
      })
			return
		}
      var formDataA = {
        name: this.formData.areaName,
        checkDate: aTime.sort().join(),
        checkType: this.formData.selectTime,
        startTime: this.formData.officeTime,
        endTime: this.formData.closingTime,
        personLableDto: aMids,
      }
      // console.log(formDataA)
      // return;
      if (this.editType == 'create') {
        const formData = _.cloneDeep(formDataA)
        const { success } = await create(formData)
        if (success) {
          this.$Message.success(this.$t('devicesCreate.devCreateS'))
          this.ifUpdateUpper = true
          this.$_modal_close()
        } else {
          this.$Message.error(this.$t('devicesCreate.devCreateN'))
        }

      } else if (this.editType == 'update') {
        formDataA.id = this.editItem.id

        const formData = _.cloneDeep(formDataA)
        console.log('formData',formData)
        const { success } = await update(formData)
        if (success) {
          this.$Message.success(this.$t('devicesCreate.devCreateUpdateS'))
          this.ifUpdateUpper = true
          this.$_modal_close()
        } else {
          this.$Message.error(this.$t('devicesCreate.devCreateUpdateN'))
        }
      }
    },
    async handleUpdate () {
      const formData = _.cloneDeep(this.formData)
      formData.departId = this.departId
      // let atime=formData.checkDate
      // console.log('atime2',atime,atime.split(',').sort().join())
      // return
      const { success } = await update(formData)
      if (success) {
        this.$Message.success(this.$t('devicesCreate.devCreateUpdateS'))
        this.ifUpdateUpper = true
        this.$_modal_close()
      } else {
        this.$Message.error(this.$t('devicesCreate.devCreateUpdateN'))
      }
    },
    async getDataList () {
      // 通过vuex调接口获取公司名depart是vuex中别的一套vuex模块
      const list = await this.$store.dispatch('depart/getList')
      let listString = JSON.stringify(list).replace(/"id"/g, '"value"')
      let listStringLabel = listString.replace(/"departName"/g, '"label"')
      let listStringChildren = listStringLabel.replace(/"children"/g, '"children"')
      var aParse = JSON.parse(listStringChildren)
      function dG(params) {
        params.forEach(v=>{
          if(v.children){
            dG(v.children)
          }else{
            v.children=[]
          }
        })
      }
      dG(aParse)
      if(aParse[0].label==="新部门"){
        let arr12 = aParse
        arr12[0].label=this.$t('title.newDepart')
        this.recordTypes=arr12
      }else{
        this.recordTypes = aParse
      }
      // console.log('this.recordTypes123')
      // console.log(this.recordTypes)
      
      setTimeout(()=>{
        let arr=[]
        arr.push(this.recordTypes[0].value) 
        this.recordType = arr
        if(!this.depId){
          // console.log('this.depId2',this.depId)
          this.depId=this.recordTypes[0].value
        }
        if(!this.departName){
          console.log('this.departName',this.departName)
          this.departName=this.recordTypes[0].label
          console.log('this.departName',this.departName)
        }
        this.getAllPersonList()
        // console.log('recordType',this.recordType)
      },500)
    },
    handleChange1 (value,selectedData) {     
      if(value.length>0){
        // this.recordType = value
        // console.log(value)
        // console.log(selectedData)
        this.personList=[]
        this.currentPage=1
        this.depId=value[value.length-1]
        this.departName=selectedData[selectedData.length-1].label
        this.getAllPersonList()
      }else{
        // this.depId=''
        // this.getData()
      } 
    },
    async getAllPersonList () {
      let result = []
      // console.log('this.depId',this.depId)
      
      const { success, data } = await selectAllPerson({
          depId:this.depId,
          // depId:'727',
          // page,
          // limit,
          // isTable,
        })
        if (success && data) {
          let res=data.data
          
          let midList=[]
          if(this.formData.mids.length>0){
            this.formData.mids.forEach(item=>{
              midList.push(item.mid)
            })
          }
          res.forEach(v=>{
            if(midList.includes(v.mid)){
              v.checked=true
            }else{
              v.checked=false
            }
          })
          this.personList=res
        }
    },
    handleSlectAll(e){
      if(this.personList){
        var da='',arr=[]
        this.personList.forEach(item => {
          // arr.push(item.mid)
          if(e){
            if(!item.checked){
              da={
                mid:item.mid,username:item.username
              }
              this.formData.mids.push(da)
            }else{

            }
            
          }else{
            arr.push(item.mid)
          }
          item.checked=e
        })
        
        if(!e){
          this.formData.mids=this.formData.mids.filter((v,i)=> {
            return !arr.includes(v.mid)
          })
        }
        
      }
    },
    itemChange(item,checked){
      item.checked=!item.checked
      let da={
        mid:item.mid,username:item.username
      }
      // console.log(da)
      if(checked){
        this.formData.mids.forEach((v,i)=> {
          if(v.mid==item.mid){
            //选择组里面有
            this.formData.mids.splice(i,1)
          }
        })
      }else{
        this.formData.mids.push(da)
      }
    },
    delPerson(item){
      // alert(index)
      this.formData.mids.forEach((v,i)=> {
        if(v.mid==item.mid){
          this.formData.mids.splice(i,1)
        }
      })
      this.getAllPersonList()
    }
  },   
}
</script>
<style lang="less" scoped>
.personList{
  // width: 80%;
  .action{
    height: 32px;
    display: flex;
      align-items: center;
    .itemTitle{
      width: 45%;
      display: inline-block;
      // display: flex;
      // align-items: center;
      &.ml{
        margin-left: 3%;
      }
      .num{
        float: right;
        margin-right: 10px;
      }
    }
    
  }
  .list {
    // flex: 1;
    // height: 400px;
    // overflow: auto;
    box-sizing: border-box;
    padding: 10px 0;
    
    .person-list{
      float: left;
      width: 45%;
      height: 400px;
      box-sizing: border-box;
      border: 1px solid #ccc;
      &.ml{
        margin-left: 3%;
      }
      .pl{
        padding-left: 10px;
        
        // text-align: center;
      }
      .person-item{
        .item-icon{
          vertical-align: middle;
        }
        .item-title{
          // display: inline;
          display: inline-block;
          margin-left: 10px;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
        .close-icon{
          // float: right;
          flex: 1;
          text-align: right;
        }
      }
    }
  }
}
.scroller {
  // height: 100%;
  height: 400px;
}

.user {
  height: 32%;
  padding: 0 12px;
  display: flex;
  align-items: center;
} 
</style>
